import setting from '@/utils/setting'
import { showToast } from '@nutui/nutui'

type options = {
  data?: Record<string, any>
  headers?: Record<string, any>
}

const request = async (url: string, method: 'POST' | 'GET' = 'GET', options?: options) => {
  const { headers, data } = options || {}

  if (method === 'GET' && data) {
    const schema = new URLSearchParams(data)
    url += '?' + schema.toString()
  }

  const body = data && method !== 'GET' ? JSON.stringify(data) : undefined

  const response = await fetch(setting.host + url, {
    method,
    body,
    headers: {
      'Content-Type': 'application/json',
      Authorization: localStorage.getItem('Authorization'),
      ...headers,
    },
  })

  const result = await response.json()

  console.log('===res', result)

  if (result.code !== 0) {
    console.log('!!')
    showToast.text(result.msg || '请求失败')
    return Promise.reject(result)
  }

  return result.data
}

export default request
